﻿using AutoMapper;
using CommonType;
using MediatR;
using S_Incident.Domains.EventHandling;
using S_Incident.Domains.WorkflowEngine;
using S_Incident.Infrasturctre.DapperInterface;
using S_Incident.Read.API.Application.Commands;

namespace S_Incident.Read.API.Application.CommandsHanders
{
    public class ProcessShowCommandHanders : IRequestHandler<ProcessShowCommand, PageResule<FormManagementProcessDto>>
    {
        private readonly IDapperProcessRepository repository;
        public ProcessShowCommandHanders(IDapperProcessRepository repository)
        {
            this.repository = repository;
        }
        /// <summary>
        /// 流程管理列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<PageResule<FormManagementProcessDto>> Handle(ProcessShowCommand request, CancellationToken cancellationToken)
        {
            var query = $"SELECT a.*, b.* FROM Process AS a INNER JOIN FormManagement AS b ON a.FormId = b.Id WHERE 1 = 1";

            if (!string.IsNullOrEmpty(request.processName))
            {
                query += $" AND a.ProcessName LIKE '%{request.processName}%'";
            }

            var totalCount = await repository.SelectAsync(request.pageSize, query);
            query += $" ORDER BY a.Id DESC LIMIT {(request.pageIndex - 1) * request.pageSize}, @PageSize;";

            // 使用 AutoMapper 进行类型转换
            var mapper = new MapperConfiguration(cfg => cfg.CreateMap<Process, FormManagementProcessDto>()).CreateMapper();

            var result = await repository.SelectAsync(request.pageSize, query);
            var formManagementProcessDtos = mapper.Map<List<FormManagementProcessDto>>(result);

            return new PageResule<FormManagementProcessDto>
            {
                TotalCount = totalCount.Count(),
                PageCount = (int)Math.Ceiling((totalCount.Count() * 1.0) / request.pageSize),
                Data = formManagementProcessDtos
            };


        }
    }

}
